<template>
  <div>
    <!-- 这里的判断要根据是管理员角色还是老师角色显示不同的内容 -->
    <el-dialog v-if="useRoute().query.roles" v-model="dialogVisible" title="教学设计" width="500" class="my_dialog">
      <template #header>
        <div class="designDialogHead">
          <p>教学设计</p>
        </div>
      </template>
      <div class="designContent">
        <div style="width: 100%" class="right">
          <div class="rightTit">已选择</div>
          <div v-for="(item, index) in selectMaterialArr" class="selectItem" :key="index">
            <template v-if="item != undefined">
              <span v-if="getFileHzm(item.name) == '.mp4'">视频</span>
              <span v-else-if="getFileHzm(item.name) == '.pdf'">课件</span>
              <span v-else>资料</span>
              <div class="row">
                <p>{{ item.name }}</p>
              </div>
            </template>
          </div>
        </div>
      </div>
    </el-dialog>

    <el-dialog v-else v-model="dialogVisible" title="教学设计" width="700" class="my_dialog">
      <template #header>
        <div class="designDialogHead">
          <p>教学设计</p>
        </div>
      </template>
      <div class="designContent">
        <div class="left">
          <div class="liNav">
            <div @click="designTab(index)" :class="tabIdx == index ? 'active' : ''" class="li"
              v-for="(item, index) in clockStatusMap" :key="item.value">
              {{ item.label }}
            </div>
          </div>

          <div class="search">
            <el-input @keyup.enter="searchMaterial" @clear="onClearInput" clearable v-model.trim="materialOption.name"
              style="max-width: 600px" placeholder="请输入搜索内容">
              <template #append><el-button @click="searchMaterial" type="primary">搜索</el-button></template>
            </el-input>
          </div>
          <div class="designList" v-loading="loading">
            <SelectMater @onRadioChange="onRadioChange" v-model:materialData="materialData" />
          </div>

          <div class="pageOut">
            <el-pagination layout="prev, pager, next" :total="materialTotal" :page-size="materialOption.page_size"
              @currentChange="currentChange" hide-on-single-page />
          </div>
        </div>

        <div class="right">
          <div class="rightTit">已选择</div>
          <div v-for="(item, index) in selectMaterialArr" class="selectItem" :key="index">
            <template v-if="item != undefined">
              <span v-if="getFileHzm(item.name) == '.mp4'">视频</span>
              <span v-else-if="getFileHzm(item.name) == '.pdf'">课件</span>
              <span v-else>资料</span>
              <div class="row">
                <el-tooltip
                              class="box-item"
                              effect="dark"
                              :content="item.name"
                              placement="top"
                            >
                <p>{{ giveEllipsisStr1(item.name, 10) }}</p>
                </el-tooltip>
                <div @click="closeMaterial(index)" class="close">×</div>
              </div>
            </template>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addDesign" :disabled="dialogDisabled">
            确认关联
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  teachDesignDetail,
  teachDesignPreview,
  upDesignDetail,
} from "@/api/chapter";
import { materialList } from "@/api/material";
import SelectMater from "./SelectMater.vue";
import { giveEllipsisStr1, getFileHzm } from "@/utils/common";
import { ElMessage, ElPopconfirm, ElLoading } from "element-plus";
import { useRoute } from "vue-router";
import { status } from "nprogress";
import { counterStore } from "@/store/modules/counter";

const courseStatus = sessionStorage.getItem("status");
const store = counterStore();
const props = defineProps({
  clockStatusMap: Array,
});
const subsection = ref();
//关联菜单选项值
const tabIdx = ref(0);
const loading = ref(true);

const materialData = ref([]); //素材列表

const materialTotal = ref(0);

const dialogDisabled = ref(false);

//更新时，通过接口获取当前教学设计完整数据
let curtCloudSlt = null;
let beforeState = false;

//获取素材的基础素材
const materialOption = ref({
  //素材列表查询条件
  name: "",
  t: 0,
  bk_id: store.bkItem.id,
  page_size: 200,
  page_num: 1,
});

const dialogVisible = ref(false);
// 选中素材之后的数组
const selectMaterialArr = ref([]);

watch(
  materialData,
  (nv) => {


    // 选中素材之后添加chechecd标记
    let find = nv.find((item) => item.checked);
    console.log(find);
    if (find) {
      console.log(find);

      let { t } = find;
      let idx = selectMaterialArr.value.findIndex(
        (item) => item && item.t == t
      );
      console.log(idx);
      if (idx < 0) {
        selectMaterialArr.value[t] = find;
      } else {
        selectMaterialArr.value[idx] = find;
      }
    } else {


    }
  },
  { deep: true }
);

//打开dialog弹框，由外部组件触发该方法
const openDialog = async (e) => {
  subsection.value = e;
  tabIdx.value = 0;
  materialOption.value.t = tabIdx.value;
  materialOption.value.name = "";
  dialogDisabled.value = false;
  dialogVisible.value = true;
  selectMaterialArr.value = [];
  materialData.value = [];
  await Promise.all([getTeachDesignDetail(), getMaterialList()]);
  beforeState = true;
};

const onRadioChange = (e) => {
  console.log(e);
};

// 点击教学设计中的标签
const designTab = (e) => {
  console.log(666);

  tabIdx.value = e;
  materialOption.value.t = e;
  getMaterialList();
};

//获取素材列表
const getMaterialList = async () => {
  loading.value = true;
  let res = await materialList(materialOption.value);
  console.log(res);

  loading.value = false;
  materialTotal.value = res.total_count;
  materialData.value = res.list;
  buildLeftOriginalMaterial();
};
// 将已选择的和获取的素材进行比对，添加checked标记
const buildLeftOriginalMaterial = () => {
  console.log(materialData.value);
  console.log(selectMaterialArr.value);
  materialData.value.forEach((item, index) => {
    selectMaterialArr.value.forEach((find) => {
      if (item.id == find.id) {
        materialData.value[index].checked = true;
      }
    });
  });
};
// 获取已选择的教学设计相关资料
const getTeachDesignDetail = async () => {
  const res = await teachDesignDetail(subsection.value.id);
  curtCloudSlt = Object.values(res);
  await teachDesignPreview(subsection.value.id).then((result) => {
    if (result.response) {
      console.log(result.response.data);
    } else {
      let teachDesignArr = [];
      for (let i = 0; i < result.length; i++) {
        for (let j = 0; j < curtCloudSlt.length; j++) {
          if (result[i].t === curtCloudSlt[j].t) {
            result[i].material_id = curtCloudSlt[j].material_id;
            teachDesignArr.push(result[i]);
            break;
          }
        }
      }
      console.log(teachDesignArr);

      selectMaterialArr.value = new Array(props.clockStatusMap.length);
      teachDesignArr.forEach((item) => {
        selectMaterialArr.value[item.t] = {
          name: item.name,
          id: item.material_id,
          url: item.url,
          t: item.t,
          file_id: item.file_id,
        };
      });
    }
  });
  buildLeftOriginalMaterial();
};

// arr=[
//   {id:19,t:0, name:"AAA"},
//   {id:20,t:1, name:"BBB"}
// ]
// arr.splice(0, 1);

// 在用splice方法根据索引删除时怎么不让后面的数据索引值改变


// 删除选中的素材
const closeMaterial = (index) => {
  materialData.value.forEach((item, idx) => {
    if (selectMaterialArr.value[index].id == item.id) {
      item.checked = false;
    }
  });


  //   // 使用 null 标记删除,解决删除后改变索引值的bug
  function deleteById(index) {
    for (let i = 0; i < selectMaterialArr.value.length; i++) {
      if (selectMaterialArr.value[i] && selectMaterialArr.value[i].t === index) {
        selectMaterialArr.value[i] = null;
        break;
      }
    }

  }
// selectMaterialArr.value.splice(index, 1);
  deleteById(index);

  console.log(materialData.value);
  console.log(selectMaterialArr.value);
};

// 点击教学设计中的搜索
const searchMaterial = () => {
  getMaterialList();
};

// 点击清空搜索框中的内容
const onClearInput = () => {
  getMaterialList();
};

// 页码改变事件
const currentChange = (e) => {
  materialOption.value.page_num = e;
  getMaterialList();
};

// 新增和更新教学设计
const addDesign = () => {
  console.log(subsection.value.id);
  //判断关联资料是不是没有任何选择
  if (selectMaterialArr.value.every((item) => !item))
    return ElMessage.error("教学设计不能为空");
  dialogDisabled.value = true;
  console.log(selectMaterialArr.value);



  let newMaterialArr = selectMaterialArr.value
    .filter((e) => e)
    .map((item) => {
      return {
        material_id: item.id,
        sort: item.t,
        t: item.t,
      }
    });



  let data = {
    out_line_id: subsection.value.id + '',
    materials: newMaterialArr

  }
  console.log(data);

  upDesignDetail(data).then((res) => {
    console.log(res);
    ElMessage.success("更新成功");
    dialogDisabled.value = false;
    dialogVisible.value = false;
  });



};

defineExpose({
  openDialog,
});
</script>

<style lang="scss" scoped>
.designContent {
  border-top: 1px solid #eee;
  border-bottom: 1px solid #eee;
  min-height: 400px;
  display: flex;

  .left {
    padding: 0 20px 20px 20px;
    width: 480px;
    border-right: 1px solid #eee;
    min-height: 400px;

    .liNav {
      border-bottom: 1px solid #eee;
      display: flex;
      align-items: flex-start;
      margin: 20px 0;

      .li {
        padding: 8px 0;
        margin-right: 36px;
        font-size: 14px;
        color: rgba(102, 102, 102, 1);
        cursor: pointer;
        border-bottom: 3px solid transparent;
        box-sizing: border-box;
      }

      .active {
        color: rgba(67, 149, 255, 1);
        border-color: rgba(67, 149, 255, 1);
      }
    }

    .search {
      margin-bottom: 20px;
    }

    .radioGroup {
      .info {
        display: flex;
        align-items: center;
        justify-content: space-between;
        width: 100%;
        padding-right: 30px;

        .infoLeft {
          display: flex;
          align-items: center;

          span {
            margin-left: 5px;
          }
        }

        .infoRight {
          color: #999;
          font-size: 12px;
        }
      }
    }

    .pageOut {
      width: 100%;
      display: flex;
      justify-content: center;
      margin-top: 40px;
    }

    .el-radio.el-radio--large {
      width: 100%;
    }

    .el-radio-group {
      display: block;
    }
  }

  .right {
    padding: 20px;
    width: 220px;
    min-height: 400px;

    .rightTit {
      font-size: 18px;
      color: #000;
      margin-bottom: 30px;
    }

    .selectItem {
      margin-bottom: 15px;

      span {
        font-size: 14px;
        color: #999;
      }

      .row {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 5px 0;

        p {}

        .close {
          width: 16px;
          height: 16px;
          background: #ccc;
          color: #fff;
          border-radius: 50%;
          text-align: center;
          line-height: 16px;
          cursor: pointer;
        }
      }
    }
  }
}
</style>
